package com.dabay.web.service;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.codec.digest.DigestUtils;

import com.dabay.web.util.Helper;
import net.sf.json.JSONObject;

/**
 * 
 * 微信公众号适用 不是企业
 * @author chenghongjun
 *
 */
public class WeixinService {
  public static void main(String[] args) {
	  
      String access_token = getAccessTokenStr("wxdaf5a4e06f8250f7","462b2d75e77fb07a19aab2d0845a721f");
	  String jsapi_ticket = getJsapi_ticketStr(access_token);
	  String noncestr = new Helper().getRandomString(16);
	  String signature = "jsapi_ticket="+jsapi_ticket;
	  		 signature+="&noncestr="+noncestr;
	  		 signature+="&timestamp="+System.currentTimeMillis()+"";
	  		 signature+="&url=http://app.nbhrss.gov.cn/nbrs_web_weixin/nbwx/m/list_detail?docid="+"284844";
	  String signatureNew = DigestUtils.shaHex(signature);
	  System.out.println(signatureNew);
	  		 
	}
	/** 
	 * 获取 微信接口调用的access_token 
	 */  	
	public static String  getAccessTokenStr(String APPID, String SECRET) {  
		String accessTokenStr = "";
	    String requestUrl = Constant.ACCESS_TOKEN;
	    requestUrl = requestUrl.replaceAll("APPID", APPID);
	    requestUrl = requestUrl.replaceAll("APPSECRET", SECRET);
	    JSONObject jsonObject = HttpRequest(requestUrl, "GET", null);  
	    // 如果请求成功  
	    if (null != jsonObject) {  
	        try {  
	        	accessTokenStr = jsonObject.getString("access_token");
	        } catch (Exception e) {  
	            // 获取token失败  
	            String error = String.format("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));  
	            System.out.println(error);
	        }  
	    }  
	    return accessTokenStr;  
	}
	
	/** 
	 * 根据access_token拿到jsapi_ticket 
	 */  	
	public static String  getJsapi_ticketStr(String accessTokenStr) {  
		String jsapi_ticket = "";
	    String requestUrl = Constant.JS_API_TICKET;
	    requestUrl = requestUrl.replaceAll("ACCESS_TOKEN", accessTokenStr);
	    JSONObject jsonObject = HttpRequest(requestUrl, "GET", null);  
	    // 如果请求成功  
	    if (null != jsonObject) {  
	        try {  
	        	jsapi_ticket = jsonObject.getString("ticket");
	        } catch (Exception e) {  
	            // 获取token失败  
	            String error = String.format("获取ticket失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));  
	            System.out.println("获取jsapi_ticketStr错误 "+error);
	        }  
	    }  
	    return jsapi_ticket;  
	}
    /** 
     * 发起https请求并获取结
     *  
     * @param requestUrl 请求地址 
     * @param requestMethod 请求方式（GET、POST
     * @param outputStr 提交的数
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性 
     */  
	public static JSONObject HttpRequest(String request , String RequestMethod , String output ){
		@SuppressWarnings("unused")
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try {
			//建立连接
			URL url = new URL(request);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod(RequestMethod);
			if(output!=null){
				OutputStream out = connection.getOutputStream();
				out.write(output.getBytes("UTF-8"));
				out.close();
			}
			//流处
			InputStream input = connection.getInputStream();
			InputStreamReader inputReader = new InputStreamReader(input,"UTF-8");
			BufferedReader reader = new BufferedReader(inputReader);
			String line;
			while((line=reader.readLine())!=null){
				buffer.append(line);
			}
			//关闭连接、释放资
			reader.close();
			inputReader.close();
			input.close();
			input = null;
			connection.disconnect();
			jsonObject = JSONObject.fromObject(buffer.toString());
		} catch (Exception e) {
		}
		return jsonObject;
	} 
}  
